package net.oschina.app.viewpagerfragment.newsdetailfragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.XRecyclerView;

import net.oschina.app.R;
import net.oschina.app.adapter.NewsItemAdapter;
import net.oschina.app.bean.News;
import net.oschina.app.bean.NewsList;
import net.oschina.app.interf.OnRecycleViewItemClickListener;
import net.oschina.app.ui.NewsItemDetailActivity;
import net.oschina.app.util.PreferencesUtils;
import net.oschina.app.util.XmlUtils;

import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Ethan on 2017/4/2.
 */

public abstract class BaseNewsFragment extends Fragment {
    public CommonFragment mCommonFragment;
    public NewsItemAdapter mAdapter;
    public NewsList mNewsList=new NewsList();
    public XRecyclerView mXrv;

    public BaseNewsFragment(){
        mCommonFragment=new CommonFragment() {
            @Override
            protected void showSuccess() {
                BaseNewsFragment.this.showSuccess();
            }

            @Override
            protected void loadData() {
                BaseNewsFragment.this.loadData();
            }
        };
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return mCommonFragment.mRootView;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser&&!mCommonFragment.isLoadData){//当Fragment可见的时候并且数据没有加载过,才去加载数据
            mCommonFragment.dynamic();
        }
    }

    public abstract int getPage();

    //成功界面
    public void showSuccess(){
        //找到列表展示控件
        mXrv = (XRecyclerView) View.inflate(getActivity(),R.layout.view_common_newsdetail_container,null);

        //设置布局管理
        LinearLayoutManager manager=new LinearLayoutManager(getContext());
        mXrv.setLayoutManager(manager);

        //设置适配器
        mAdapter = new NewsItemAdapter(getContext(),mNewsList);
        mAdapter.notifyDataSetChanged();
        mXrv.setAdapter(mAdapter);

        //设置可以下拉刷新和加载更多
        mXrv.setPullRefreshEnabled(true);
        mXrv.setLoadingMoreEnabled(true);

        //处理事件
        initEvent();

        //切换界面
        mCommonFragment.changeView(mXrv);
    };

    //事件处理方法
    private void initEvent() {
        //条目的点击时事件
        mAdapter.setOnItemClickListener(new OnRecycleViewItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                position-=1;
                News news = mNewsList.getList().get(position);

                //从SP中获取保存的资讯ids
                String ids = PreferencesUtils.getString(getContext(), "news_id", "");

                //判断获取到的ids是否包含当前点击的id
                if (!ids.contains(news.getId()+"")){//没有被点击过
                    ids+=news.getId();
                    //将新组合的ids储存到SP
                    PreferencesUtils.putString(getContext(),"news_id",ids);
                }
                TextView tvItemTitle= (TextView) view.findViewById(R.id.tv_newsdetail_title);
                tvItemTitle.setTextColor(Color.parseColor("#838383"));
                Intent intent=new Intent(getActivity(), NewsItemDetailActivity.class);
                intent.putExtra("id",news.getId());
                startActivity(intent);
            }
        });

        //设置加载监听
        mXrv.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                mXrv.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                mXrv.loadMoreComplete();
            }
        });
    }

    //加载数据
    public void loadData(){
        //获取OkHttp对象
        OkHttpClient client=new OkHttpClient();

        //获取网络地址
        int page=getPage();

        //获取请求
        Request request=new Request.Builder().url("http://10.0.2.2:8080/oschina/list/news/page"+page+".xml").build();
        Call call=client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                mCommonFragment.dealCommonFail();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取响应流
                InputStream inputStream = response.body().byteStream();

                //通过XmlUtils工具获取Bean类
                mNewsList = XmlUtils.toBean(NewsList.class, inputStream);

                mCommonFragment.dealCommonSuccess();
            }
        });
    };
}
